#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , manager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);
    this->setWindowTitle("TextManager");
    this->setFixedSize(1600,900);        QPushButton *saveBtn = new QPushButton("保存结果", this);
    saveBtn->setFont(QFont("华文楷体", 20));
    saveBtn->move(1300, 700);
    connect(saveBtn, &QPushButton::clicked, this, &Widget::saveProcessedText);


    QFont font("华文楷体",30,20,0);
    ui->loadInButton->setFont(font);
    ui->loadInButton->move(300,700);

    ui->startButton->setFont(font);
    ui->startButton->move(1000,700);

    ui->saveBtn->setFont(font);
    ui->saveBtn->move(1300, 700);

    ui->fileLabel->setText("当前未选择文件");
    ui->fileLabel->setWordWrap(true);
    ui->fileLabel->setFixedSize(800,200);
    ui->fileLabel->setFont(font);

    ui->textEdit->setFixedSize(600,300);
    ui->textEdit->move(800,200);

    connect(saveBtn, &QPushButton::clicked, this, &Widget::saveProcessedText);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_loadInButton_clicked()
{
    openFileDialog();
}

void Widget::openFileDialog()
{
    fileName = QFileDialog::getOpenFileName(
        this,
        "选择文件",
        QDir::homePath(),
        "Word文档 (*.docx);;文本文件 (*.txt)"
        );

    if (fileName.isEmpty()) return;

    QFile file(fileName);

    if(QFileInfo(fileName).suffix().toLower() == "docx")
    {
        originalText = extractDocxText(fileName);
    }
    else
    {
        if(file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            originalText = file.readAll();
            file.close();
        }
        else
        {
            QMessageBox::warning(this,"错误","无法打开文件");
        }
    }
    ui->textEdit->setPlainText("原始内容:\n" + originalText);

    QFileInfo info(fileName);
    ui->fileLabel->setText(QString("文件名：%1\n 大小：%2 KB\n 路径：%3").arg(info.fileName()).arg(info.size()/1024).arg(info.path()));
}

void Widget::on_startButton_clicked()
{
    if (originalText.isEmpty())
    {
        QMessageBox::warning(this, "警告", "请先选择文本文件");
        return;
    }

    QNetworkRequest request(QUrl("http://localhost:1234/v1/chat/completions"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject jsonBody;
    jsonBody["temperature"] = 0.7;
    jsonBody["max_tokens"] = -1;
    jsonBody["stream"] = false;

    QJsonArray messages;
    QJsonObject systemMsg;
    systemMsg["role"] = "system";
    systemMsg["content"] = "请保持原有格式对文本进行专业润色，不要修改格式结构。要求：修改后文本总字数 ≥ 原文字数 × 1.1";
    messages.append(systemMsg);

    QJsonObject userMsg;
    userMsg["role"] = "user";
    userMsg["content"] = originalText;
    messages.append(userMsg);

    jsonBody["messages"] = messages;

    QNetworkReply *reply = manager->post(request, QJsonDocument(jsonBody).toJson());
    connect(reply, &QNetworkReply::finished, [this, reply]() {
        handleApiResponse(reply);
    });
}

void Widget::handleApiResponse(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        QJsonDocument response = QJsonDocument::fromJson(reply->readAll());
        QJsonObject jsonResponse = response.object();

        QString rawText = jsonResponse["choices"].toArray()[0].toObject()
                              ["message"].toObject()["content"].toString();

        //去除<think>标签及内容
        processedText = rawText.replace(
            QRegularExpression("<think>.*?</think>",
                               QRegularExpression::DotMatchesEverythingOption),
            ""
            );

        ui->textEdit->append("\n\n处理结果:\n" + processedText);
    }
    else
    {
        QMessageBox::critical(this, "错误", "请求失败: " + reply->errorString());
    }
    reply->deleteLater();
}

void Widget::saveProcessedText()
{
    QString fileName = QFileDialog::getSaveFileName(
        this,
        "保存文件",
        QDir::homePath() + "/processed_text.txt",
        "文本文件 (*.txt)"
        );

    if (!fileName.isEmpty())
    {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream stream(&file);
            stream << processedText;
            file.close();
            QMessageBox::information(this, "成功", "文件保存成功");
            return;
        }
    }
}

QString Widget::extractDocxText(const QString &docxPath)
{
    QTemporaryDir tempDir;
    if (!tempDir.isValid()) {
        return "[错误] 无法创建临时目录";
    }
    QProcess process;
    QString cmd;
    QStringList args;

#ifdef Q_OS_WINDOWS
    cmd = "tar";
    args << "-xf" << docxPath << "-C" << tempDir.path();
#else
    cmd = "unzip";
    args << "-qq" << docxPath << "-d" << tempDir.path();
#endif

    process.start(cmd, args);

    QFile xmlFile(tempDir.path() + "/word/document.xml");
    if (!xmlFile.open(QIODevice::ReadOnly)) {
        return "[错误] 找不到内容文件";
    }

    return parseDocxXml(xmlFile.readAll());
}

QString Widget::parseDocxXml(const QByteArray &xmlData) {
    QXmlStreamReader xml(xmlData);
    QString text;
    const QString ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement() && xml.name() == QLatin1String("t")) {
            text += xml.readElementText() + " ";
        }
        if (xml.isEndElement() && xml.name() == QLatin1String("p")) {
            text += "\n";
        }
    }

    return text.simplified();

}

